/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.report.statistics.usertask;

import com.koron.common.bean.DepartmentTreeBean;
import com.koron.common.bean.DeptBean;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.KpiStatistics;
import com.koron.common.mapper.KpiStatisticsMapper;
import com.koron.common.web.Util;
import com.koron.purpose.domain.KPITemplate;
import com.koron.purpose.mapper.KPITemplateMapper;
import com.koron.report.bean.StatisticsBean;
import com.koron.report.management.StatisticsManagement;
import com.koron.report.mapper.statistics.UserTaskRateStatisticsMapper;
import com.koron.report.statistics.StatisticsService;

import com.koron.risk.bean.CorpBean;
import com.koron.risk.service.api.CorpManagementService;
import com.koron.system.domain.District;
import com.koron.system.domain.DistrictCorpRelation;
import com.koron.system.mapper.DistrictMapper;
import com.koron.system.service.api.DistrictService;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class UserTaskRateStatisticsServiceImpl  implements StatisticsService, InitializingBean {

    private final static  Logger logger= LoggerFactory.getLogger(UserTaskRateStatisticsServiceImpl.class);

    @Autowired
    private StatisticsManagement statisticsManagement;

    @Autowired
    private Util util;

    @Autowired
    private CorpManagementService corpManagementService;

    @Autowired
    private DistrictService districtService;

    private static String FINISHED_USERTASK="0112";
    private static String ALL_USERTASK="0111";
    private static String FINISHED_USERTASK_RATE="0110";
    @Override
    public void afterPropertiesSet() throws Exception {
        Set<Object> handlers = statisticsManagement.getHandlers();
        handlers.add(this);
    }
    @Override
    public void statisticsMonth(int year, int month) {
        try {
            //设置好时间
            Calendar calendar=Calendar.getInstance();
            calendar.set(year, month-1,1,0,0,0);
            Date startTime=calendar.getTime();
            calendar.set(year, month,1,0,0,0);
            Date endTime=calendar.getTime();
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM");
            int dateType=1;
            //计算计划完成
            countUserTaskFinish(simpleDateFormat,dateType,startTime,endTime);
            //计算实际完成
            countUserTaskTotal(simpleDateFormat,dateType,startTime,endTime);
            //计算任务完成率
            countUserTaskRate(simpleDateFormat,dateType,startTime,endTime);
        }catch (Exception e){
            logger.error("检查计划执行率按月统计各项指标计算失败，失败原因为："+e.getMessage());
        }
    }

    @Override
    public void statisticsQuarter(int year, int quarter) {
        try {
            Calendar calendar=Calendar.getInstance();
            int month=0;
            switch (quarter){
                case 1:
                    break;
                case 2:
                    month=3;
                    break;
                case 3:
                    month=6;
                    break;
                case 4:
                    month=9;
                    break;
                default:
                    break;
            }
            calendar.set(year, month,1,0,0,0);
            Date startTime=calendar.getTime();
            calendar.set(year, month+2,1,0,0,0);
            Date endTime=calendar.getTime();
            int dateType=2;
            //计算计划完成
            countUserTaskFinish(null,dateType,startTime,endTime);
            //计算实际完成
            countUserTaskTotal(null,dateType,startTime,endTime);
            //计算任务完成率
            countUserTaskRate(null,dateType,startTime,endTime);
        }catch (Exception e){
            logger.error("检查计划执行率按月统计各项指标计算失败，失败原因为："+e.getMessage());
        }
    }

    @Override
    public void statisticsYear(int year) {
        try {
            //设置好时间
            Calendar calendar=Calendar.getInstance();
            calendar.set(year, 0,1,0,0,0);
            Date startTime=calendar.getTime();
            calendar.set(year+1, 0,1,0,0,0);
            Date endTime=calendar.getTime();
            int dateType=3;
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy");
            //计算计划完成
            countUserTaskFinish(simpleDateFormat,dateType,startTime,endTime);
            //计算实际完成
            countUserTaskTotal(simpleDateFormat,dateType,startTime,endTime);
            //计算任务完成率
            countUserTaskRate(simpleDateFormat,dateType,startTime,endTime);
        }catch (Exception e){
            logger.error("检查计划执行率按月统计各项指标计算失败，失败原因为："+e.getMessage());
        }
    }

    /**
     * 计算实际完成的任务，指标库code为0112，部分统计层级
     * @param dateType  日期类型，1代表是月份，2代表是季度，3代表是年
     * @param startTime 开始时间
     * @param endTime 结束时间
     */
    public void countUserTaskFinish(SimpleDateFormat format,Integer dateType,Date startTime,Date endTime){
        SessionFactory factory=null;
       try{
           factory=new SessionFactory();
           //先删除
           String dateValue=getDateValue(dateType,startTime);
           factory.getMapper(KpiStatisticsMapper.class).delete(FINISHED_USERTASK,dateValue,null);
           //按人员计算
           countUserTaskFinishOrTotalByPerson(factory,format,2,dateType,startTime,endTime,FINISHED_USERTASK);
           //按部门计算
           countUserTaskFinishOrTotalByDept(factory,format,2,dateType,startTime,endTime,FINISHED_USERTASK);
           //按水司计算
           countUserTaskFinishOrTotalByCorp(factory,format,2,dateType,startTime,endTime,FINISHED_USERTASK);
           //按片区计算
           countUserTaskFinishOrTotalByDitrict(factory,format,2,dateType,startTime,endTime,FINISHED_USERTASK);
           //按集团计算
           countUserTaskFinishOrTotalByGroup(factory,format,2,dateType,startTime,endTime,FINISHED_USERTASK);
           factory.close();
       } catch (Exception e){
           if(null!=factory)
               factory.close(false);
           logger.error(e.getMessage(),e);
           logger.error(e.getMessage(),e);
       }
    }

    /**
     * 计算计划完成的任务总数，指标库code为0111，部分统计层级
     * @param dateType  日期类型，1代表是月份，2代表是季度，3代表是年
     * @param startTime 开始时间
     * @param endTime 结束时间
     */
    public void countUserTaskTotal(SimpleDateFormat format,Integer dateType,Date startTime,Date endTime){
        SessionFactory factory=null;
        try{
            factory=new SessionFactory();
            //先删除
            String dateValue=getDateValue(dateType,startTime);
            factory.getMapper(KpiStatisticsMapper.class).delete(ALL_USERTASK,dateValue,null);
            //按人员计算
            countUserTaskFinishOrTotalByPerson(factory,format,null,dateType,startTime,endTime,ALL_USERTASK);
            //按部门计算
            countUserTaskFinishOrTotalByDept(factory,format,null,dateType,startTime,endTime,ALL_USERTASK);
            //按水司计算
            countUserTaskFinishOrTotalByCorp(factory,format,null,dateType,startTime,endTime,ALL_USERTASK);
            //按片区计算
            countUserTaskFinishOrTotalByDitrict(factory,format,null,dateType,startTime,endTime,ALL_USERTASK);
            //按集团计算
            countUserTaskFinishOrTotalByGroup(factory,format,null,dateType,startTime,endTime,ALL_USERTASK);
            factory.close();
        } catch (Exception e){
            if(null!=factory)
                factory.close(false);
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
        }
    }

    public void countUserTaskRate(SimpleDateFormat format,Integer dateType,Date startTime,Date endTime){
        SessionFactory factory=null;
        try{
            factory=new SessionFactory();
            //先删除
            String dateValue=getDateValue(dateType,startTime);
            factory.getMapper(KpiStatisticsMapper.class).delete(FINISHED_USERTASK_RATE,dateValue,null);
            //按人员计算
            countUserTaskFinishRateByPerson(factory,format,dateType,startTime,endTime);
            //按部门计算
            countUserTaskFinishRateByDept(factory,format,dateType,startTime,endTime);
            //按水司计算
            countUserTaskFinishRateByCorp(factory,format,dateType,startTime,endTime);
            //按片区计算
            countUserTaskFinishRateByDitrict(factory,format,dateType,startTime,endTime);
            //按集团计算
            countUserTaskFinishRateByGroup(factory,format,dateType,startTime,endTime);
            factory.close();
        } catch (Exception e){
            if(null!=factory)
                factory.close(false);
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
        }
    }

    /**
     * 设置kpi指标的通用数据值
     * @param template
     * @param type 日期类型，1代表是月份，2代表是季度，3代表是年
     * @param date 日期
     * @return
     */
    private KpiStatistics generateKpiStatistics(KPITemplate template,Integer type,Date date){
        KpiStatistics kpiStatistics=new KpiStatistics();
        kpiStatistics.setKpiId(template.getId());
        kpiStatistics.setKpiCode(template.getCode());
        kpiStatistics.setKpiName(template.getName());
        //判断如何设置日期，1代表是月份，2代表是季度，3代表是年
        kpiStatistics.setDateType(type);
        kpiStatistics.setDateValue(getDateValue(type,date));
        return  kpiStatistics;
    }

    /**
     *根据日期和日期类型，获取相应的日期字符串
     * 月份返回形如2020-02，季度返回2020-1，年返回2020
     * @param type 日期类型，1代表是月份，2代表是季度，3代表是年
     * @param date  日期
     * @return
     */
    private String getDateValue(Integer type,Date date){
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(date);
        int year=calendar.get(Calendar.YEAR);
        int month=calendar.get(Calendar.MONTH)+1;
        switch (type){
            case 1:
                return ""+year+"-"+(month<10?"0"+month:month);
            case 2:
                return ""+year+"-"+(month/3+1);
            case 3:
                return year+"";
            default:
                return "";
        }
    }

    /**
     * 查询任务实际完成多少或者计划完成多少,根据参数countType来区分,统计层级为人员
     * @param countType 不传，统计指定时间计划完成的，传2：统计指定时间实际完成的
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param kpiTemplateCode 指标库code
     * @throws Exception
     */
    public void countUserTaskFinishOrTotalByPerson(SessionFactory factory, SimpleDateFormat format,Integer countType, Integer dateType, Date startTime,
                                                   Date endTime,String kpiTemplateCode) throws Exception {
        KpiStatisticsMapper kpiStatisticsMapper=factory.getMapper(KpiStatisticsMapper.class);
        KPITemplateMapper templateMapper=factory.getMapper(KPITemplateMapper.class);
        UserTaskRateStatisticsMapper userTaskRateStatisticsMapper=factory.getMapper(UserTaskRateStatisticsMapper.class);
        //查询对应的指标库
        KPITemplate template=templateMapper.queryTemplateByCode(kpiTemplateCode);
        //存储要被插入的数据
        List<KpiStatistics> kpiStatisticsList=null;
        List<StatisticsBean> statisticsBeanList=userTaskRateStatisticsMapper.countUserTaskFinishOrTotalByPerson(countType,startTime,endTime);
        if (null!=statisticsBeanList&&statisticsBeanList.size()>0){
            kpiStatisticsList=new ArrayList<>();
            Date date=new Date();
            for(StatisticsBean statisticsBean:statisticsBeanList){
                //由于数据问题，在统计时没有办法取到人的姓名，在此之前需要根据员工code获取员工名称
                List<StaffBean> staffBeanList= (List<StaffBean>) util.staff(statisticsBean.getCode(),null).getData();
                //员工确实存在
                if (null!=staffBeanList&&staffBeanList.size()>0){
                    KpiStatistics kpiStatistics=generateKpiStatistics(template,dateType,startTime);
                    kpiStatistics.setKpiValue(Float.parseFloat(statisticsBean.getValue()));
                    kpiStatistics.setObjectId(statisticsBean.getCode());
                    kpiStatistics.setObjectName(staffBeanList.get(0).getName());
                    kpiStatistics.setStatisticalType(1);
                    kpiStatistics.setAddTime(date);
                    kpiStatisticsList.add(kpiStatistics);
                }
            }
        }
        //将获取的统计数据批量插入
        if(null!=kpiStatisticsList&&kpiStatisticsList.size()>0){
            Integer value=kpiStatisticsMapper.batchInsert(kpiStatisticsList);
            if(value<0){
                String a=dateType==2?getDateValue(dateType,startTime):format.format(startTime);
                throw new Exception(a +"计算指标库code为"+kpiTemplateCode + "，统计层级为员工失败");
            }
        }
    }

    /**
     * 查询任务实际完成多少或者计划完成多少,根据参数countType来区分,统计层级为部门
     * @param countType 不传，统计指定时间计划完成的，传2：统计指定时间实际完成的
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param kpiTemplateCode 指标库code
     * @throws Exception
     */
    public void countUserTaskFinishOrTotalByDept(SessionFactory factory, SimpleDateFormat format,Integer countType, Integer dateType, Date startTime,
                                                 Date endTime,String kpiTemplateCode) throws Exception{
        KpiStatisticsMapper kpiStatisticsMapper=factory.getMapper(KpiStatisticsMapper.class);
        KPITemplateMapper templateMapper=factory.getMapper(KPITemplateMapper.class);
        UserTaskRateStatisticsMapper userTaskRateStatisticsMapper=factory.getMapper(UserTaskRateStatisticsMapper.class);
        //查询对应的指标库
        KPITemplate template=templateMapper.queryTemplateByCode(kpiTemplateCode);
        //存储要被插入的数据
        List<KpiStatistics> kpiStatisticsList=null;
        List<StatisticsBean> statisticsBeanList=userTaskRateStatisticsMapper.countUserTaskFinishOrTotalByPerson(countType,startTime,endTime);
        if (null!=statisticsBeanList&&statisticsBeanList.size()>0){
            kpiStatisticsList=new ArrayList<>();
            Date date=new Date();
            for(StatisticsBean statisticsBean:statisticsBeanList){
                //由于数据问题，在统计时没有办法取到部门的名称，在此之前需要根据部门code获取部门名称
                List<DeptBean> departmentTreeBeanList= (List<DeptBean>) util.dept(statisticsBean.getCode()).getData();
                //员工确实存在
                if (null!=departmentTreeBeanList&&departmentTreeBeanList.size()>0){
                    KpiStatistics kpiStatistics=generateKpiStatistics(template,dateType,startTime);kpiStatistics.setKpiValue(Float.parseFloat(statisticsBean.getValue()));
                    kpiStatistics.setObjectId(statisticsBean.getCode());
                    kpiStatistics.setObjectName(departmentTreeBeanList.get(0).getName());
                    kpiStatistics.setStatisticalType(2);
                    kpiStatistics.setAddTime(date);
                    kpiStatisticsList.add(kpiStatistics);
                }
            }
        }
        //将获取的统计数据批量插入
        if(null!=kpiStatisticsList&&kpiStatisticsList.size()>0){
            Integer value=kpiStatisticsMapper.batchInsert(kpiStatisticsList);
            if(value<0){
                String a=dateType==2?getDateValue(dateType,startTime):format.format(startTime);
                throw new Exception(a+"计算指标库code为"+kpiTemplateCode + "，统计层级为部门失败");
            }
        }
    }

    /**
     * 查询任务实际完成多少或者计划完成多少,根据参数countType来区分,统计层级为水司
     * @param countType 不传，统计指定时间计划完成的，传2：统计指定时间实际完成的
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param kpiTemplateCode 指标库code
     * @throws Exception
     */
    public void countUserTaskFinishOrTotalByCorp(SessionFactory factory, SimpleDateFormat format,Integer countType, Integer dateType, Date startTime,
                                                 Date endTime,String kpiTemplateCode) throws Exception{
        KpiStatisticsMapper kpiStatisticsMapper=factory.getMapper(KpiStatisticsMapper.class);
        KPITemplateMapper templateMapper=factory.getMapper(KPITemplateMapper.class);
        UserTaskRateStatisticsMapper userTaskRateStatisticsMapper=factory.getMapper(UserTaskRateStatisticsMapper.class);
        //查询对应的指标库
        KPITemplate template=templateMapper.queryTemplateByCode(kpiTemplateCode);
        //存储要被插入的数据
        List<KpiStatistics> kpiStatisticsList=null;
        //查询当前所有水司
        List<CorpBean> corpBeanList=corpManagementService.corpBeanList();
        if (null!=corpBeanList&&corpBeanList.size()>0){
            kpiStatisticsList=new ArrayList<>();
            Date date=new Date();
            for(CorpBean corpBean:corpBeanList){
                //查询当前水司的所所有部门
                List<DepartmentTreeBean> departmentTreeBeanList= (List<DepartmentTreeBean>) util.depttree(corpBean.getCorpCode(),1).getData();
                //存储当前水司下所有部门的code
                List<String> codeList=new ArrayList<>();
                if (departmentTreeBeanList!=null&&departmentTreeBeanList.size()>0){
                    codeList=departmentTreeBeanList.stream().map(DepartmentTreeBean::getDepartmentCode).collect(Collectors.toList());
                    if (codeList!=null&&codeList.size()>0){
                        Integer result=userTaskRateStatisticsMapper.countUserTaskFinishOrTotalByCorpOrDitrictOrGroup(countType,startTime,endTime,codeList);
                        if (result>0){
                            KpiStatistics kpiStatistics=generateKpiStatistics(template,dateType,startTime);kpiStatistics.setKpiValue(Float.parseFloat(result.toString()));
                            kpiStatistics.setObjectId(corpBean.getCorpCode());
                            kpiStatistics.setObjectName(corpBean.getCorpName());
                            kpiStatistics.setStatisticalType(3);
                            kpiStatistics.setAddTime(date);
                            kpiStatisticsList.add(kpiStatistics);
                        }
                    }
                }
            }
        }
        //将获取的统计数据批量插入
        if(null!=kpiStatisticsList&&kpiStatisticsList.size()>0){
            Integer value=kpiStatisticsMapper.batchInsert(kpiStatisticsList);
            if(value<0){
                String a=dateType==2?getDateValue(dateType,startTime):format.format(startTime);
                throw new Exception(a+"计算指标库code为"+kpiTemplateCode + "，统计层级为水司失败");
            }
        }
    }

    /**
     * 查询任务实际完成多少或者计划完成多少,根据参数countType来区分,统计层级为片区
     * @param countType 不传，统计指定时间计划完成的，传2：统计指定时间实际完成的
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param kpiTemplateCode 指标库code
     * @throws Exception
     */
    public void countUserTaskFinishOrTotalByDitrict(SessionFactory factory, SimpleDateFormat format,Integer countType, Integer dateType, Date startTime,
                                                 Date endTime,String kpiTemplateCode) throws Exception{
        KpiStatisticsMapper kpiStatisticsMapper=factory.getMapper(KpiStatisticsMapper.class);
        KPITemplateMapper templateMapper=factory.getMapper(KPITemplateMapper.class);
        UserTaskRateStatisticsMapper userTaskRateStatisticsMapper=factory.getMapper(UserTaskRateStatisticsMapper.class);
        DistrictMapper districtMapper=factory.getMapper(DistrictMapper.class);
        //查询对应的指标库
        KPITemplate template=templateMapper.queryTemplateByCode(kpiTemplateCode);
        //存储要被插入的数据
        List<KpiStatistics> kpiStatisticsList=null;
        List<District> districtList=districtMapper.queryAllDistrict(null,null);
        if (null!=districtList&&districtList.size()>0){
            Date date=new Date();
            kpiStatisticsList=new ArrayList<>();
            for(District district:districtList){
                //查询当前片区下所有水司
                List<DistrictCorpRelation> relationList=districtService.queryDistrictCorp(district.getCode(),null,null).getData().getList();
                List<String> codeList=new ArrayList<>();
                if (null!=relationList&&relationList.size()>0){
                    for(DistrictCorpRelation corpBean:relationList){
                        //查询当前水司的所所有部门
                        List<DepartmentTreeBean> departmentTreeBeanList= (List<DepartmentTreeBean>) util.depttree(corpBean.getCorpCode(),1).getData();
                        //存储当前水司下所有部门的code
                        if (departmentTreeBeanList!=null&&departmentTreeBeanList.size()>0){
                            codeList=departmentTreeBeanList.stream().map(DepartmentTreeBean::getDepartmentCode).collect(Collectors.toList());
                        }
                    }
                }
                if (codeList!=null&&codeList.size()>0){
                    Integer result=userTaskRateStatisticsMapper.countUserTaskFinishOrTotalByCorpOrDitrictOrGroup(countType,startTime,endTime,codeList);
                    if (result>0){
                        KpiStatistics kpiStatistics=generateKpiStatistics(template,dateType,startTime);kpiStatistics.setKpiValue(Float.parseFloat(result.toString()));
                        kpiStatistics.setObjectId(district.getCode());
                        kpiStatistics.setObjectName(district.getName());
                        kpiStatistics.setStatisticalType(4);
                        kpiStatistics.setAddTime(date);
                        kpiStatisticsList.add(kpiStatistics);
                    }
                }
            }
        }
        //将获取的统计数据批量插入
        if(null!=kpiStatisticsList&&kpiStatisticsList.size()>0){
            Integer value=kpiStatisticsMapper.batchInsert(kpiStatisticsList);
            if(value<0){
                String a=dateType==2?getDateValue(dateType,startTime):format.format(startTime);
                throw new Exception(a+"计算指标库code为"+kpiTemplateCode + "，统计层级为片区失败");
            }
        }
    }

    /**
     * 查询任务实际完成多少或者计划完成多少,根据参数countType来区分,统计层级为片区
     * @param countType 不传，统计指定时间计划完成的，传2：统计指定时间实际完成的
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param kpiTemplateCode 指标库code
     * @throws Exception
     */
    public void countUserTaskFinishOrTotalByGroup(SessionFactory factory, SimpleDateFormat format,Integer countType, Integer dateType, Date startTime,
                                                    Date endTime,String kpiTemplateCode) throws Exception{
        KpiStatisticsMapper kpiStatisticsMapper=factory.getMapper(KpiStatisticsMapper.class);
        KPITemplateMapper templateMapper=factory.getMapper(KPITemplateMapper.class);
        UserTaskRateStatisticsMapper userTaskRateStatisticsMapper=factory.getMapper(UserTaskRateStatisticsMapper.class);
        //查询对应的指标库
        KPITemplate template=templateMapper.queryTemplateByCode(kpiTemplateCode);
        //存储要被插入的数据
        List<KpiStatistics> kpiStatisticsList=new ArrayList<>();
        Date date=new Date();
        Integer result=userTaskRateStatisticsMapper.countUserTaskFinishOrTotalByCorpOrDitrictOrGroup(countType,startTime,endTime,null);
        KpiStatistics kpiStatistics=generateKpiStatistics(template,dateType,startTime);kpiStatistics.setKpiValue(Float.parseFloat(result.toString()));
        kpiStatistics.setObjectId("c75d5edacbc042448dab01951208421b");
        kpiStatistics.setObjectName("粤海水资源");
        kpiStatistics.setStatisticalType(5);
        kpiStatistics.setAddTime(date);
        kpiStatisticsList.add(kpiStatistics);
        //将获取的统计数据批量插入
        if(null!=kpiStatisticsList&&kpiStatisticsList.size()>0){
            Integer value=kpiStatisticsMapper.batchInsert(kpiStatisticsList);
            if(value<0){
                String a=dateType==2?getDateValue(dateType,startTime):format.format(startTime);
                throw new Exception(a+"计算指标库code为"+kpiTemplateCode + "，统计层级为集团失败");
            }
        }
    }

    /**
     * 任务完成率，指标库code为0110，统计层级为人员
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @throws Exception
     */
    public void countUserTaskFinishRateByPerson(SessionFactory factory, SimpleDateFormat format,Integer dateType,Date startTime,Date endTime) throws Exception{
        KpiStatisticsMapper kpiStatisticsMapper=factory.getMapper(KpiStatisticsMapper.class);
        KPITemplateMapper templateMapper=factory.getMapper(KPITemplateMapper.class);
        UserTaskRateStatisticsMapper userTaskRateStatisticsMapper=factory.getMapper(UserTaskRateStatisticsMapper.class);
        //查询对应的指标库
        KPITemplate template=templateMapper.queryTemplateByCode(FINISHED_USERTASK_RATE);
        //存储要被插入的数据
        List<KpiStatistics> kpiStatisticsList=null;
        //计划完成的
        List<StatisticsBean> totalStatisticsBeanList=userTaskRateStatisticsMapper.countUserTaskFinishOrTotalByPerson(null,startTime,endTime);
        //实际完成的
        List<StatisticsBean> actualStatisticsBeanList=userTaskRateStatisticsMapper.countUserTaskFinishOrTotalByPerson(null,startTime,endTime);
        if (null!=totalStatisticsBeanList&&totalStatisticsBeanList.size()>0){
            kpiStatisticsList=new ArrayList<>();
            Date date=new Date();
            for(StatisticsBean statisticsBean:totalStatisticsBeanList){
                //由于数据问题，在统计时没有办法取到人的姓名，在此之前需要根据员工code获取员工名称
                List<StaffBean> staffBeanList= (List<StaffBean>) util.staff(statisticsBean.getCode(),null).getData();
                //员工确实存在
                if (null!=staffBeanList&&staffBeanList.size()>0){
                    List<StatisticsBean> temp=actualStatisticsBeanList.stream().filter(s->s.getCode().equals(statisticsBean.getCode())).collect(Collectors.toList());
                    Float actual=0F;
                    if (null!=temp&&temp.size()>0){
                        actual=Float.parseFloat(temp.get(0).getValue());
                    }
                    KpiStatistics kpiStatistics=generateKpiStatistics(template,dateType,startTime);kpiStatistics.setKpiValue(actual/Float.parseFloat(statisticsBean.getValue()));
                    kpiStatistics.setObjectId(statisticsBean.getCode());
                    kpiStatistics.setObjectName(staffBeanList.get(0).getName());
                    kpiStatistics.setStatisticalType(1);
                    kpiStatistics.setAddTime(date);
                    kpiStatisticsList.add(kpiStatistics);
                }
            }
        }
        //将获取的统计数据批量插入
        if(null!=kpiStatisticsList&&kpiStatisticsList.size()>0){
            Integer value=kpiStatisticsMapper.batchInsert(kpiStatisticsList);
            if(value<0){
                String a=dateType==2?getDateValue(dateType,startTime):format.format(startTime);
                throw new Exception(a+"计算指标库code为"+FINISHED_USERTASK_RATE + "，统计层级为员工失败");
            }
        }
    }

    /**
     * 任务完成率，指标库code为0110，统计层级为人员
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @throws Exception
     */
    public void countUserTaskFinishRateByDept(SessionFactory factory, SimpleDateFormat format,Integer dateType,Date startTime,Date endTime) throws Exception{
        KpiStatisticsMapper kpiStatisticsMapper=factory.getMapper(KpiStatisticsMapper.class);
        KPITemplateMapper templateMapper=factory.getMapper(KPITemplateMapper.class);
        UserTaskRateStatisticsMapper userTaskRateStatisticsMapper=factory.getMapper(UserTaskRateStatisticsMapper.class);
        //查询对应的指标库
        KPITemplate template=templateMapper.queryTemplateByCode(FINISHED_USERTASK_RATE);
        //存储要被插入的数据
        List<KpiStatistics> kpiStatisticsList=null;
        //计划完成的
        List<StatisticsBean> totalStatisticsBeanList=userTaskRateStatisticsMapper.countUserTaskFinishOrTotalByDept(null,startTime,endTime);
        //实际完成的
        List<StatisticsBean> actualStatisticsBeanList=userTaskRateStatisticsMapper.countUserTaskFinishOrTotalByDept(null,startTime,endTime);
        if (null!=totalStatisticsBeanList&&totalStatisticsBeanList.size()>0){
            kpiStatisticsList=new ArrayList<>();
            Date date=new Date();
            for(StatisticsBean statisticsBean:totalStatisticsBeanList){
                //由于数据问题，在统计时没有办法取到部门的名称，在此之前需要根据部门code获取部门名称
                List<DeptBean> departmentTreeBeanList= (List<DeptBean>) util.dept(statisticsBean.getCode()).getData();
                //员工确实存在
                if (null!=departmentTreeBeanList&&departmentTreeBeanList.size()>0){
                    List<StatisticsBean> temp=actualStatisticsBeanList.stream().filter(s->s.getCode().equals(statisticsBean.getCode())).collect(Collectors.toList());
                    Float actual=0F;
                    if (null!=temp&&temp.size()>0){
                        actual=Float.parseFloat(temp.get(0).getValue());
                    }
                    KpiStatistics kpiStatistics=generateKpiStatistics(template,dateType,startTime);kpiStatistics.setKpiValue(actual/Float.parseFloat(statisticsBean.getValue()));
                    kpiStatistics.setObjectId(statisticsBean.getCode());
                    kpiStatistics.setObjectName(departmentTreeBeanList.get(0).getName());
                    kpiStatistics.setStatisticalType(1);
                    kpiStatistics.setAddTime(date);
                    kpiStatisticsList.add(kpiStatistics);
                }
            }
        }
        //将获取的统计数据批量插入
        if(null!=kpiStatisticsList&&kpiStatisticsList.size()>0){
            Integer value=kpiStatisticsMapper.batchInsert(kpiStatisticsList);
            if(value<0){
                String a=dateType==2?getDateValue(dateType,startTime):format.format(startTime);
                throw new Exception(a+"计算指标库code为"+FINISHED_USERTASK_RATE + "，统计层级为部门失败");
            }
        }
    }

    /**
     * 任务完成率，指标库code为0110，统计层级为水司
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @throws Exception
     */
    public void countUserTaskFinishRateByCorp(SessionFactory factory, SimpleDateFormat format, Integer dateType, Date startTime,
                                                 Date endTime) throws Exception{
        KpiStatisticsMapper kpiStatisticsMapper=factory.getMapper(KpiStatisticsMapper.class);
        KPITemplateMapper templateMapper=factory.getMapper(KPITemplateMapper.class);
        UserTaskRateStatisticsMapper userTaskRateStatisticsMapper=factory.getMapper(UserTaskRateStatisticsMapper.class);
        //查询对应的指标库
        KPITemplate template=templateMapper.queryTemplateByCode(FINISHED_USERTASK_RATE);
        //存储要被插入的数据
        List<KpiStatistics> kpiStatisticsList=null;
        //查询当前所有水司
        List<CorpBean> corpBeanList=corpManagementService.corpBeanList();
        if (null!=corpBeanList&&corpBeanList.size()>0){
            kpiStatisticsList=new ArrayList<>();
            Date date=new Date();
            for(CorpBean corpBean:corpBeanList){
                //查询当前水司的所所有部门
                List<DepartmentTreeBean> departmentTreeBeanList= (List<DepartmentTreeBean>) util.depttree(corpBean.getCorpCode(),1).getData();
                //存储当前水司下所有部门的code
                List<String> codeList=new ArrayList<>();
                if (departmentTreeBeanList!=null&&departmentTreeBeanList.size()>0){
                    codeList=departmentTreeBeanList.stream().map(DepartmentTreeBean::getDepartmentCode).collect(Collectors.toList());
                    if (codeList!=null&&codeList.size()>0){
                        Integer result=userTaskRateStatisticsMapper.countUserTaskFinishOrTotalByCorpOrDitrictOrGroup(null,startTime,endTime,codeList);
                        if (result>0){
                            Integer actual=userTaskRateStatisticsMapper.countUserTaskFinishOrTotalByCorpOrDitrictOrGroup(2,startTime,endTime,codeList);
                            KpiStatistics kpiStatistics=generateKpiStatistics(template,dateType,startTime);
                            kpiStatistics.setKpiValue(Float.parseFloat(actual.toString())/Float.parseFloat(result.toString()));
                            kpiStatistics.setObjectId(corpBean.getCorpCode());
                            kpiStatistics.setObjectName(corpBean.getCorpName());
                            kpiStatistics.setStatisticalType(3);
                            kpiStatistics.setAddTime(date);
                            kpiStatisticsList.add(kpiStatistics);
                        }
                    }
                }
            }
        }
        //将获取的统计数据批量插入
        if(null!=kpiStatisticsList&&kpiStatisticsList.size()>0){
            Integer value=kpiStatisticsMapper.batchInsert(kpiStatisticsList);
            if(value<0){
                String a=dateType==2?getDateValue(dateType,startTime):format.format(startTime);
                throw new Exception(a+"计算指标库code为"+FINISHED_USERTASK_RATE + "，统计层级为水司失败");
            }
        }
    }

    /**
     * 任务完成率，指标库code为0110，统计层级为片区
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @throws Exception
     */
    public void countUserTaskFinishRateByDitrict(SessionFactory factory, SimpleDateFormat format,Integer dateType, Date startTime,
                                                    Date endTime) throws Exception{
        KpiStatisticsMapper kpiStatisticsMapper=factory.getMapper(KpiStatisticsMapper.class);
        KPITemplateMapper templateMapper=factory.getMapper(KPITemplateMapper.class);
        UserTaskRateStatisticsMapper userTaskRateStatisticsMapper=factory.getMapper(UserTaskRateStatisticsMapper.class);
        DistrictMapper districtMapper=factory.getMapper(DistrictMapper.class);
        //查询对应的指标库
        KPITemplate template=templateMapper.queryTemplateByCode(FINISHED_USERTASK_RATE);
        //存储要被插入的数据
        List<KpiStatistics> kpiStatisticsList=null;
        List<District> districtList=districtMapper.queryAllDistrict(null,null);
        if (null!=districtList&&districtList.size()>0){
            Date date=new Date();
            kpiStatisticsList=new ArrayList<>();
            for(District district:districtList){
                //查询当前片区下所有水司
                List<DistrictCorpRelation> relationList=districtService.queryDistrictCorp(district.getCode(),null,null).getData().getList();
                List<String> codeList=new ArrayList<>();
                if (null!=relationList&&relationList.size()>0){
                    for(DistrictCorpRelation corpBean:relationList){
                        //查询当前水司的所所有部门
                        List<DepartmentTreeBean> departmentTreeBeanList= (List<DepartmentTreeBean>) util.depttree(corpBean.getCorpCode(),1).getData();
                        //存储当前水司下所有部门的code
                        if (departmentTreeBeanList!=null&&departmentTreeBeanList.size()>0){
                            codeList=departmentTreeBeanList.stream().map(DepartmentTreeBean::getDepartmentCode).collect(Collectors.toList());
                        }
                    }
                }
                if (codeList!=null&&codeList.size()>0){
                    Integer result=userTaskRateStatisticsMapper.countUserTaskFinishOrTotalByCorpOrDitrictOrGroup(null,startTime,endTime,codeList);
                    if (result>0){
                        Integer actual=userTaskRateStatisticsMapper.countUserTaskFinishOrTotalByCorpOrDitrictOrGroup(2,startTime,endTime,codeList);
                        KpiStatistics kpiStatistics=generateKpiStatistics(template,dateType,startTime);
                        kpiStatistics.setKpiValue(Float.parseFloat(actual.toString())/Float.parseFloat(result.toString()));
                        kpiStatistics.setObjectName(district.getName());
                        kpiStatistics.setObjectId(district.getCode());
                        kpiStatistics.setStatisticalType(4);
                        kpiStatistics.setAddTime(date);
                        kpiStatisticsList.add(kpiStatistics);
                    }
                }
            }
        }
        //将获取的统计数据批量插入
        if(null!=kpiStatisticsList&&kpiStatisticsList.size()>0){
            Integer value=kpiStatisticsMapper.batchInsert(kpiStatisticsList);
            if(value<0){
                String a=dateType==2?getDateValue(dateType,startTime):format.format(startTime);
                throw new Exception(a+"计算指标库code为"+FINISHED_USERTASK_RATE + "，统计层级为片区失败");
            }
        }
    }

    /**
     * 任务完成率，指标库code为0110，统计层级为集团
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @throws Exception
     */
    public void countUserTaskFinishRateByGroup(SessionFactory factory, SimpleDateFormat format, Integer dateType, Date startTime,
                                                  Date endTime) throws Exception{
        KpiStatisticsMapper kpiStatisticsMapper=factory.getMapper(KpiStatisticsMapper.class);
        KPITemplateMapper templateMapper=factory.getMapper(KPITemplateMapper.class);
        UserTaskRateStatisticsMapper userTaskRateStatisticsMapper=factory.getMapper(UserTaskRateStatisticsMapper.class);
        //查询对应的指标库
        KPITemplate template=templateMapper.queryTemplateByCode(FINISHED_USERTASK_RATE);
        //存储要被插入的数据
        List<KpiStatistics> kpiStatisticsList=new ArrayList<>();
        Date date=new Date();
        Integer result=userTaskRateStatisticsMapper.countUserTaskFinishOrTotalByCorpOrDitrictOrGroup(null,startTime,endTime,null);
        Integer actual=userTaskRateStatisticsMapper.countUserTaskFinishOrTotalByCorpOrDitrictOrGroup(2,startTime,endTime,null);
        KpiStatistics kpiStatistics=generateKpiStatistics(template,dateType,startTime);kpiStatistics.setKpiValue(Float.parseFloat(actual.toString())/Float.parseFloat(result.toString()));
        kpiStatistics.setObjectId("c75d5edacbc042448dab01951208421b");
        kpiStatistics.setObjectName("粤海水资源");
        kpiStatistics.setStatisticalType(5);
        kpiStatistics.setAddTime(date);
        kpiStatisticsList.add(kpiStatistics);
        //将获取的统计数据批量插入
        if(null!=kpiStatisticsList&&kpiStatisticsList.size()>0){
            Integer value=kpiStatisticsMapper.batchInsert(kpiStatisticsList);
            if(value<0){
                String a=dateType==2?getDateValue(dateType,startTime):format.format(startTime);
                throw new Exception(a+"计算指标库code为"+FINISHED_USERTASK_RATE + "，统计层级为集团失败");
            }
        }
    }

}
